package com.example.emailcraft.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class JwtUtil {
    // 配置参数（建议从配置文件读取）
    private static final String SECRET = "emailcraft-secret-key-1234567890abcdefghij";
    private static final long EXPIRATION = 86400000L; // 24小时
    private static final SecretKey SECRET_KEY = Keys.hmacShaKeyFor(SECRET.getBytes());
    private static final String CLAIM_USER_ID = "uid";
    private static final String CLAIM_ROLES = "roles";

    // 生成令牌
    public static String generateToken(Long userId, String username, String roles) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_USER_ID, userId);
        claims.put(CLAIM_ROLES, roles);

        return Jwts.builder()
                .setClaims(claims)
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION))
                .signWith(SECRET_KEY, SignatureAlgorithm.HS256)
                .compact();
    }

    // 解析用户ID
    public static Long getUserId(String token) {
        return parseToken(token).get(CLAIM_USER_ID, Long.class);
    }

    // 解析用户名
    public static String getUsername(String token) {
        return parseToken(token).getSubject();
    }

    // 解析角色
    public static String getRoles(String token) {
        return parseToken(token).get(CLAIM_ROLES, String.class);
    }

    // 验证令牌
    public static boolean validateToken(String token) {
        try {
            parseToken(token);
            return true;
        } catch (JwtException e) {
            return false;
        }
    }
    // 获取 JWT 的过期时间
    public static long getExpiration() {
        return EXPIRATION;
    }
    private static Claims parseToken(String token) {
        if (StringUtils.isBlank(token)) {
            throw new JwtException("令牌不能为空");
        }
        return Jwts.parserBuilder()
                .setSigningKey(SECRET_KEY)
                .build()
                .parseClaimsJws(token)
                .getBody();
    }
}
